package com.ldx.blog.sevice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ldx.blog.common.exception.BlogException;
import com.ldx.blog.common.utils.SecurityUtils;
import com.ldx.blog.mapper.BlogInfoMapper;
import com.ldx.blog.mapper.UserInfoMapper;
import com.ldx.blog.pojo.dataobject.BlogInfo;
import com.ldx.blog.pojo.dataobject.UserInfo;
import com.ldx.blog.pojo.request.UserLoginRequest;
import com.ldx.blog.pojo.response.UserInfoResponse;
import com.ldx.blog.pojo.response.UserLoginResponse;
import com.ldx.blog.sevice.UserService;
import com.ldx.blog.common.utils.JwtUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    BlogInfoMapper blogInfoMapper;
    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest) throws BlogException {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag,0)
                .eq(UserInfo::getUserName,userLoginRequest.getUserName());
        UserInfo userInfo =  userInfoMapper.selectOne(queryWrapper);
        if(userInfo == null){
            throw new BlogException("用户不存在");
        }
//        if(!userLoginRequest.getPassword().equals(userInfo.getPassword())){
//            throw new BlogException("密码错误");
//        }
        //使用加盐加密验证
       if(!SecurityUtils.verify(userLoginRequest.getPassword(),userInfo.getPassword())){
           throw new BlogException("密码错误");
       }else {
           Map<String,Object> clams = new HashMap<>();
           clams.put("userId",userInfo.getId());
           clams.put("userName",userInfo.getUserName());
           String token = JwtUtils.genToken(clams);
           return new UserLoginResponse(userInfo.getId(),token);
       }

    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo> queryWrapper= new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag,0)
                .eq(UserInfo::getId,userId);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        return UserInfoResponse.trans(userInfo);
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) throws BlogException {
        QueryWrapper<BlogInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BlogInfo::getDeleteFlag,0)
                .eq(BlogInfo::getId,blogId);
        BlogInfo blogInfo = blogInfoMapper.selectOne(queryWrapper);
        Integer userId = blogInfo.getUserId();
        UserInfoResponse userInfo = getUserInfo(userId);
        return userInfo;

    }
}
